package com.gzcstec.web;

import com.alibaba.druid.support.json.JSONUtils;
import com.gzcstec.domain.Host;
import com.gzcstec.service.HostService;
import com.gzcstec.service.HostStatService;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.hibernate.validator.internal.util.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;

import java.util.logging.Logger;

/**
 * 微信将网页授权相关
 * Created by fan on 2017/10/19.
 */
@Controller
@RequestMapping("/wechat")
public class WechatController {

    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(WechatController.class);

    @Autowired
    private WxMpService wxOpenService;

    @Autowired
    private HostService hostService;

    @Autowired
    private HostStatService hostStatService;

    /**
     * js方式扫码登录
     * @param code
     * @return
     */
    @RequestMapping(value = "/qrAuthByJs" , method = RequestMethod.GET)
    public String qrAuthorizeByJs(@RequestParam("code") String code ,
                                  @RequestParam("returnURL") String returnURL ,
                                  @RequestParam("state") String state) {

        //判断returnURL是否可信
        //验证签名
        log.info("code:"+code+",returnURL:"+returnURL+",state:"+state);
        Host host = hostService.getByState(state);
        if(null == host || !StringUtils.trim(host.getReturnUrl()).equals(returnURL)) {
            log.info("签名验证不通过!");
            return "50x";
        }

        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
        try {
            wxMpOAuth2AccessToken = wxOpenService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        String openId = wxMpOAuth2AccessToken.getOpenId();

        //记录openid,用于数据统计使用
        hostStatService.updateHostStat(openId , host.getHostId());

        return "redirect:" + returnURL + "?openid=" + openId;
    }

//    @RequestMapping("/index")
//    public String index() {
//        return "index";
//    }

}
